package com.example.archive.controller;

import com.example.archive.util.Result;
import com.example.archive.service.OCRService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/ocr")
@CrossOrigin(origins = "*")
public class OCRController {
    
    @Autowired
    private OCRService ocrService;
    
    /**
     * OCR文字识别接口
     * @param file 上传的图片文件
     * @return 识别结果
     */
    @PostMapping("/recognize")
    public Result<String> recognizeText(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.fail(400, "请选择要识别的图片文件");
            }
            
            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !isImageFile(contentType)) {
                return Result.fail(400, "请上传图片文件（支持JPG、PNG、GIF、BMP等格式）");
            }
            
            // 检查文件大小（限制4MB）
            if (file.getSize() > 4 * 1024 * 1024) {
                return Result.fail(400, "图片文件大小不能超过4MB");
            }
            
            String recognizedText = ocrService.recognizeText(file);
            
            if (recognizedText.startsWith("OCR识别失败")) {
                return Result.fail(500, recognizedText);
            }
            
            return Result.success(recognizedText);
            
        } catch (Exception e) {
            return Result.fail(500, "OCR识别异常: " + e.getMessage());
        }
    }
    
    /**
     * 判断是否为图片文件
     */
    private boolean isImageFile(String contentType) {
        return contentType.equals("image/jpeg") ||
               contentType.equals("image/jpg") ||
               contentType.equals("image/png") ||
               contentType.equals("image/gif") ||
               contentType.equals("image/bmp") ||
               contentType.equals("image/webp");
    }
} 